package response

import "github.com/gin-gonic/gin"

type AjaxResult struct {
	Result map[string]interface{} // 返回结果
}

func NewAjaxResult() *AjaxResult {
	return &AjaxResult{
		Result: map[string]interface{}{
			"code": 0,
			"msg":  "",
		},
	}
}
func NewAjaxResultSuccess() *AjaxResult {
	return &AjaxResult{
		Result: map[string]interface{}{
			"code": 0,
			"msg":  "操作成功",
			"data": nil,
		},
	}
}
func (a *AjaxResult) SetData(data any) {
	a.Result["data"] = data
}
func (a *AjaxResult) SetMsg(msg string) {
	a.Result["msg"] = msg
}
func (a *AjaxResult) SetCode(code int) {
	a.Result["code"] = code
}
func (a *AjaxResult) Success(data interface{}) *AjaxResult {
	a.Result = map[string]interface{}{
		"code": 200,
		"msg":  "操作成功",
		"data": data,
	}
	return a
}

func (a *AjaxResult) Put(key string, value interface{}) {
	a.Result[key] = value
}

func (a *AjaxResult) Fail(code int, msg string) *AjaxResult {
	a.Result = map[string]interface{}{
		"code": code,
		"msg":  msg,
		"data": nil,
	}
	return a
}

func (a *AjaxResult) GetResult() map[string]interface{} {
	return a.Result
}

// ============================================================================
func AjaxFail(ctx *gin.Context, code int, msg string) {
	result := NewAjaxResult().Fail(code, msg).Result
	ctx.JSON(200, result)
}
func AjaxFailCode(ctx *gin.Context, code int) {
	result := NewAjaxResult().Fail(code, "操作失败").Result
	ctx.JSON(200, result)
}
func AjaxError(ctx *gin.Context, err error) {
	result := NewAjaxResult().Fail(500, err.Error()).Result
	ctx.JSON(200, result)
}
func AjaxSuccess(ctx *gin.Context, data any) {
	result := NewAjaxResult().Success(data).Result
	ctx.JSON(200, result)
}
func AjaxDataTable(ctx *gin.Context, list any, total int64) {
	result := NewAjaxResult()
	result.SetCode(200)
	result.SetMsg("查询成功")
	result.Put("rows", list)
	result.Put("total", total)
	ctx.JSON(200, result.Result)
}
func AjaxResponse(ctx *gin.Context, ajaxResult *AjaxResult) {
	ctx.JSON(200, ajaxResult.Result)
}
